""" PsyBlockGame module """

if __name__ == '__main__':
    import os
    import sys
    PATH_DIRS = [
        r'\bin\lib',
        r'\bin\lib\site-packages',
        r'\src',
    ]
    sys.path = [os.getcwd() + path for path in PATH_DIRS]

import os
import pickle
import zlib
import io
from PsyBlockGame.Game import GameConfig
from PyQt4.QtCore import QObject
from PyQt4.QtGui import QMessageBox, QApplication

SETTINGS_SAVE = r".\data\settings.bin"

try:
    os.mkdir(".\\data\\")
except:
    pass

TABLE = '0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

def StrToNum(text):
    return [TABLE.index(ch) for ch in text]

def NumToStr(nums):
    return ''.join([TABLE[index] for index in nums])

class Data:
    pass

class ApplicationConfig(QObject):
    __slots__ = (
        'adminPassword',
        'isConfigModified',
        'isEnglishLang',
        'lastName',
        'currentConfig',
        'namedConfigs')

    def __init__(self):
        self.adminPassword = NumToStr([26, 15, 11, 12, 22, 15, 29])
        self.isConfigModified = False
        self.isEnglishLang = True
        self.lastName = ""
        self.currentConfig = GameConfig()
        self.namedConfigs = {}

    def save(self):
        obj = Data()
        for name in self.__slots__:
            setattr(obj, name, getattr(self, name))

        stream = io.BytesIO()
        stream.write(pickle.dumps(obj))
        bin = zlib.compress(stream.getvalue())

        try:
            f = open(SETTINGS_SAVE, "wb")
            f.write(bin)
            f.close()
        except:
            QMessageBox.critical(None, self.tr("Cannot save settings"), self.tr("Cannot open file '%s' for writing") % SETTINGS_SAVE)

    def load(self):
        if not os.access(SETTINGS_SAVE, os.F_OK):
            return

        try:
            f = open(SETTINGS_SAVE, "rb")
            bin = f.read()
            f.close()
        except:
            QMessageBox.warning(None, self.tr("Failed to load settings"), self.tr("Cannot open file '%s' for reading") % SETTINGS_SAVE)
            return

        data = zlib.decompress(bin)
        obj = pickle.loads(data)

        for name in self.__slots__:
            if hasattr(obj, name):
                setattr(self, name, getattr(obj, name))

        self.currentConfig.validate()
        for v in self.namedConfigs.values():
            v.validate()

if __name__ == '__main__':
    SETTINGS_SAVE = DATA_PATH + "settings_test.bin"

    qApp = QApplication(sys.argv)

    cfg = ApplicationConfig()
    cfg.currentConfig.figures = "TEST"
    cfg.save()

    cfg = ApplicationConfig()
    cfg.load()

    assert cfg.currentConfig.figures == "TEST"